<template>
  <div id="wangeditor">
    <nav-header @getIndex="getNum($event)"></nav-header>
    <div class="title">文章编辑</div>
    <div class="ctn">
      <div class="subimt-content">
        <div class="submit-talk">
          <div class="submit-icon">
            <img src="../assets/imgs/lbiaoqian.png" />
          </div>
          <div class="submit-title submitTag">选择专题</div>
          <div class="selModule">
            <div
              class="singleModule"
              v-for="(item, index) in module"
              :key="index"
            >
              <input
                type="radio"
                name="module"
                id
                class="radioStyle"
                :value="item.tagId"
                v-model="interestId"
                @change="getModule(item.tagId)"
              />
              <label for>{{ item.tagName }}</label>
            </div>
          </div>
        </div>
        <div class="submit-talk" @click="selTalk">
          <div class="submit-icon talkIcon">
            <img src="../assets/imgs/bq.png" />
          </div>
          <div class="submit-title">{{ talk }}</div>
        </div>
        <div class="submit-stars">
          <div class="stars-title">【来闻指数】</div>
          <div class="stars" v-for="(item, index) in stars" :key="index">
            <div @click="getStars(index)">
              <img src="../assets/imgs/beizi.png" v-if="item.show" />
              <img src="../assets/imgs/hb.png" v-else />
            </div>
          </div>
          <div class="starText" v-if="starsShow">{{ prompt }}</div>
          <div class="starText" v-else-if="starsNum == 4">
            <img src="../assets/imgs/five.png" alt />
          </div>
        </div>
        <input
          type="text"
          placeholder="请输入标题"
          class="ipt-title"
          v-model="title"
          @input="titleChange($event)"
        />
        <div
          ref="editorElem"
          id="editorElem"
          style="text-align:left;"
          v-loading="loading"
        ></div>
        <div class="btns">
          <div
            class="submit-button saveDrafts"
            @click="saveDrafts(1)"
            v-if="isRevise"
          >
            存草稿
          </div>
          <div class="submit-button saveDrafts" v-else @click="revise(1)">
            修改
          </div>
          <div class="submit-button" @click="submit(0)">发布</div>
          <div class="submit-button back" @click="back('index')">返回</div>
        </div>
      </div>
    </div>
    <Talk @sendTalk="getTalk" ref="talk" :interestId='interestId'></Talk>
    <nav-footer ref="child"></nav-footer>
    <div></div>
  </div>
</template>
<script>
import E from "wangeditor";
import NavHeader from "../components/Header";
import Talk from "../components/Talk";
import NavFooter from "../components/Footer";
export default {
  name: "Editor",
  data() {
    return {
      editor: null,
      editorContent: "",
      html: "",
      article: {},
      content: "",
      pics: [],
      stars: [{}, {}, {}, {}, {}],
      show: false,
      number: 9,
      totalNum: 0,
      title: "",
      starsNum: "",
      talk: "选择话题",
      index: "index",
      module: "",
      interestId:0,
      prompt: "",
      starsShow: false,
      articleId: 0,
      obj: "",
      loading: false,
      isRevise: true,
    };
  },
  components: {
    NavHeader,
    NavFooter,
    Talk,
  },
  created() {
    //初始化锁
    localStorage.setItem("locked", 0);
    //获取用户信息
    let user = JSON.parse(localStorage.getItem("user"));
    console.log(user);
    this.$set(this.article, "headImage", user.headImage);
    this.$set(this.article, "nickName", user.nickName);
    this.$set(this.article, "articleUserId", user.id);
    //初始化加载星星
    for (let i of this.stars.keys()) {
      this.$set(this.stars[i], "show", true);
    }
    if (this.$route.query.id == void 0) {
      this.init();
    } else {
      //  加载草稿箱
      this.articleId = this.$route.query.id;
      this.loadDrafts();
      this.init();
      //判断显示修改按钮
      this.isRevise = false;
    }
  },
  mounted() {
    this.getRem(1920, 100);
    this.editor = new E(this.$refs.editorElem);
    this.editor.customConfig.menus = ["image", "fontSize", "justify", "bold"];
    this.editor.customConfig.pasteFilterStyle = false;
     // 忽略粘贴内容中的图片
    this.editor.customConfig.pasteIgnoreImg = true
    // 编辑器的事件，每次改变会获取其html内容
    let editorText = null;
    this.editor.customConfig.onchange = (html) => {
      this.html = html;
    };
    let that = this;
    that.editor.customConfig.customUploadImg = function(files, insert) {
      let fileLen = files.length;
      for (let i = 0; i < fileLen; i++) {
        let file = files[i];
        console.log(file);
        let reader = new FileReader();
        let url = "";
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          console.log(e);
          let url = e.currentTarget.result;
          //上传到服务器
          that.$post(`/laiwen/upload/file/baseimage`, url).then((res) => {
            insert(res.downUrl);
            that.pics.push(res.downUrl);
          });
        };
      }
      console.log(that.pics);
    };
    // content 即粘贴过来的内容（html 或 纯文本），可进行自定义处理然后返回
    that.editor.customConfig.pasteTextHandle = function(content) {
      if (content == "" && !content) return "";
      let str = content;
      str = str.replace(/<xml>[\s\S]*?<\/xml>/gi, "");
      str = str.replace(/<style>[\s\S]*?<\/style>/gi, "");
      str = str.replace(/<\/?[^>]*>/g, "");
      str = str.replace(/[ | ]*\n/g, "\n");
      str = str.replace(/&nbsp;/gi, "");
      that.content = str;
      return str
    };
    this.editor.customConfig.uploadImgShowBase64 = true; // 使用 base64 保存图片

    this.editor.create(); // 创建富文本实例
  },
  methods: {
    //主函数
    init() {
      //模块列表
      this.$fetch(`/laiwen/interest/frontend/list`, {}).then((res) => {
        this.module = res.interestList;
      });
    },
    debounce(fn, wait) {
      let timer = null;
      return function() {
        if (timer !== null) {
          clearTimeout(timer);
        }
        timer = setTimeout(fn, wait);
      };
    },
    //标题字数限制(中文:2字符,英文:1字符)
    titleChange(e) {
      let val = e.target.value;
      let strLen = 0;
      let maxlength = 32;
      for (let i = 0; i < val.trim().length; i++) {
        if (/[\u4e00-\u9fa5]/.test(val[i])) {
          strLen += 2;
        } else {
          strLen++;
        }
        if (strLen > maxlength) {
          this.title = val.substr(0, i);
          let locked = localStorage.getItem("locked");
          if (locked == 0) {
            // 加锁阻止弹窗重复
            localStorage.setItem("locked", 1);
            this.$message.warning("标题最多可以输入16个字符");
            setTimeout(() => {
              localStorage.setItem("locked", 0);
            }, 1000);
          }
          break;
        }
      }
    },
    //发布文章
    submit(state) {
      let content = this.editor.txt.text();
      //正则过滤转义字符
      let artReg = /&(lt|gt|nbsp;|amp|quot|)/gi;
      this.content = content.replace(artReg, "").trim();
      this.$set(this.article, "articleState", state);
      this.$set(this.article, "talk", this.talk);
      this.$set(this.article, "articleInterestId", this.interestId);
      this.$set(this.article, "articleHtml", this.editor.txt.html());
      this.$set(this.article, "articleContent", this.content);
      this.$set(this.article, "articleTitle", this.title);
      this.$set(this.article, "award", this.starsNum);
      //匹配出所有img标签，为了监听删除
      let reg = /<img.*?src="(.*?)".*?\/?>/gi;
      let html = this.article.articleHtml;
      let picArr = [];
      picArr = html.match(reg);
      //存放图片
      let imgArrary = [];
      if (picArr != null) {
        for (let i of picArr.keys()) {
          //匹配出所有src后的路径
          let res = picArr[i].match(/src=[\'\"]?([^\'\"]*)[\'\"]?/i)[1];
          imgArrary.push(res);
        }
      }
      let pic = imgArrary.join(",");
      this.$set(this.article, "articlePicture", pic);
      //当talk为选择话题=null
      if (this.article.talk === "选择话题") {
        this.article.talk = null;
      }
      //发布文章(标题内容和话题不能为空)
      if (
        this.editor.txt.html() == "" ||
        this.title == "" ||
        this.interestId == ""
      ) {
        this.$message.error("亲亲请先输入内容和标题还有模块哦");
      } else {
        this.loading = true;

        // 从草稿箱中发布文章的判断操作
        if (
          this.article.articleTitle != null &&
           
          this.article.articleTitle != null &&
          this.article.articleInterestId
        ) {
          this.$post(`/laiwen/article/frontend/publish`, this.article).then(
            (res) => {
              console.log(this.article);
              if (res.msg == "发布成功") {
                this.loading = false;
                this.$router.push({
                  path: "/index",
                });
              } else {
                this.$message.error("发布文章失败请联系管理员");
              }
            }
          );
        } else {
          this.loading = false;
          this.$message.error("亲亲请先输入内容和标题还有模块哦");
        }
      }
    },
    //存草稿
    saveDrafts(state) {
      let content = this.editor.txt.text();
      //正则过滤转义字符
      let artReg = /&(lt|gt|nbsp;|amp|quot|)/gi;
      this.content = content.replace(artReg, "").trim();
      this.$set(this.article, "articleState", state);
      this.$set(this.article, "talk", this.talk);
      this.$set(this.article, "articleInterestId", this.interestId);
      this.$set(this.article, "articleHtml", this.editor.txt.html());
      this.$set(this.article, "articleContent", this.content);
      this.$set(this.article, "articleTitle", this.title);
      this.$set(this.article, "award", this.starsNum);
      //匹配出所有img标签，为了监听删除
      let reg = /<img.*?src="(.*?)".*?\/?>/gi;
      let html = this.article.articleHtml;
      let picArr = [];
      picArr = html.match(reg);
      //存放图片
      let imgArrary = [];
      if (picArr != null) {
        for (let i of picArr.keys()) {
          //匹配出所有src后的路径
          let res = picArr[i].match(/src=[\'\"]?([^\'\"]*)[\'\"]?/i)[1];
          imgArrary.push(res);
        }
      }
      let pic = imgArrary.join(",");
      this.$set(this.article, "articlePicture", pic);
      this.$post(`/laiwen/article/frontend/publish`, this.article).then(
        (res) => {
          console.log(res);
          console.log(this.article);
          if (res.msg == "发布成功") {
            this.loading = false;
            this.$router.push({
              path: "/drafts",
            });
          } else {
            this.$message.error("存储草稿失败请联系管理员");
          }
        }
      );
    },
    //获取头部模态窗的索引值
    getNum(e) {
      console.log(`现在的索引值是${e}`);
      this.ctnIndex = e;
    },
    // 星星方法(从0开始算)
    getStars(e) {
      //索引加一
      this.starsNum = e;
      for (let i of this.stars.keys()) {
        this.$set(this.stars[i], "show", true);
      }
      //根据索引值点亮星星
      for (let i = 0; i <= e; i++) {
        this.$set(this.stars[i], "show", false);
      }
      console.log(`星星颗数${this.starsNum + 1}`);
      //根据星星展示提示文字
      console.log(e);
      switch (e) {
        case 0:
          this.prompt = "很不香";
          this.starsShow = true;
          break;
        case 1:
          this.prompt = "不太香";
          this.starsShow = true;
          break;
        case 2:
          this.prompt = "一般香";
          this.starsShow = true;
          break;
        case 3:
          this.prompt = "非常香";
          this.starsShow = true;
          break;
        case 4:
          this.prompt = "真香警告";
          this.starsShow = false;
          break;
      }
    },
    //选择模块
    getModule(id) {
      this.interestId = id;
    },
    //返回主页
    back(name) {
      this.navigate(name);
    },
    getTalk() {
      this.talk = this.$refs.talk.content;
    },
    //获取话题模态窗
    selTalk() {
      this.$refs.talk.clear();
    },
    //加载草稿箱的内容
    loadDrafts() {
      this.$post(`/laiwen/article/frontend/info/${this.articleId}`, {}).then(
        (res) => {
          this.article = res.article;
          this.arr_path = res.article.articlePicture.split(",");
          this.title = this.article.articleTitle;
          this.interestId = this.article.articleInterestId;
          this.talk = this.article.talk;
          if (this.talk == null) {
            this.talk = "选择话题";
          }
          if (this.article.award != null) {
            this.draftsStar(this.article.award);
          }
          //插入Html
          this.editor.txt.html(this.article.articleHtml);
        }
      );
    },
    //草稿箱特有星星方法
    draftsStar: function(num) {
      this.getStars(num);
    },
    //修改草稿
    revise(state) {
      let content = this.editor.txt.text();
      //正则过滤转义字符
      let artReg = /&(lt|gt|nbsp;|amp|quot|)/gi;
      this.content = content.replace(artReg, "").trim();
      this.$set(this.article, "articleState", state);
      this.$set(this.article, "talk", this.talk);
      this.$set(this.article, "articleInterestId", this.interestId);
      this.$set(this.article, "articleHtml", this.editor.txt.html());
      this.$set(this.article, "articleContent", this.content);
      this.$set(this.article, "articleTitle", this.title);
      this.$set(this.article, "award", this.starsNum);
      //匹配出所有img标签，为了监听删除
      let reg = /<img.*?src="(.*?)".*?\/?>/gi;
      let html = this.article.articleHtml;
      let picArr = [];
      picArr = html.match(reg);
      //存放图片
      let imgArrary = [];
      if (picArr != null) {
        for (let i of picArr.keys()) {
          //匹配出所有src后的路径
          let res = picArr[i].match(/src=[\'\"]?([^\'\"]*)[\'\"]?/i)[1];
          imgArrary.push(res);
        }
      }
      let pic = imgArrary.join(",");
      this.$set(this.article, "articlePicture", pic);
      this.$post(`/laiwen/article/frontend/updatedraft`, this.article).then(
        (res) => {
          console.log(res);
          console.log(this.article);
          if (res.msg == "success") {
            this.loading = false;
            this.$message.success("修改成功");
            this.$router.push(`/drafts`);
          } else {
            this.$message.error("修改草稿失败请联系管理员");
          }
        }
      );
    },
  },
};
</script>
<style scoped src="../assets/css/editor.css"></style>
